<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Search, ArrowLeft, Calendar, User } from '@element-plus/icons-vue'
import { getUserBorrowingHistory, renewBook } from '@/api/user'

const router = useRouter()

// 搜索和筛选
const searchQuery = ref('')
const filterStatus = ref('')
const sortOrder = ref('desc')
const dateRange = ref([])

// 分页参数
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 借阅历史数据
interface BorrowRecord {
  id: number
  bookTitle: string
  author: string
  borrowDate: string
  returnDate: string
  status: string
  coverImage: string
  description: string
}

const borrowingHistory = ref<BorrowRecord[]>([])
const loading = ref(false)

// 获取借阅历史数据
const fetchBorrowingHistory = async () => {
  loading.value = true
  try {
    const data = {
      pageNumber: currentPage.value,
      pageSize: pageSize.value,
      status: filterStatus.value,
      startDate: dateRange.value?.[0] ? dateRange.value[0] : '',
      endDate: dateRange.value?.[1] ? dateRange.value[1] : '',
      keyword: searchQuery.value || ''
    }

    const res = await getUserBorrowingHistory(data)
    if (res.code === 0) {
      borrowingHistory.value = res.data.records
      total.value = res.data.total
    }
  } catch (error) {
    ElMessage.error('获取借阅历史失败')
  } finally {
    loading.value = false
  }
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchBorrowingHistory()
}

// 处理筛选
const handleFilter = () => {
  currentPage.value = 1
  fetchBorrowingHistory()
}

// 处理排序
const handleSort = () => {
  sortOrder.value = sortOrder.value === 'asc' ? 'desc' : 'asc'
  fetchBorrowingHistory()
}

// 处理续借
const handleRenew = async (record: BorrowRecord) => {
  try {
    // 模拟API调用延迟
    await new Promise(resolve => setTimeout(resolve, 500))
    ElMessage.success('续借申请已提交')
    // 这里不需要刷新数据，因为是静态数据
  } catch (error) {
    ElMessage.error('续借申请失败')
  }
}

// 处理页码变化
const handlePageChange = (page: number) => {
  currentPage.value = page
  fetchBorrowingHistory()
}

// 处理每页条数变化
const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  fetchBorrowingHistory()
}

// 返回主页
const goBack = () => {
  router.push('/user')
}

// 查看详情
const selectedBook = ref<BorrowRecord | null>(null)
const dialogVisible = ref(false)

const showDetails = (record: BorrowRecord) => {
  selectedBook.value = record
  dialogVisible.value = true
}

// 获取状态标签类型
const getStatusType = (status: string) => {
  switch (status) {
    case '已归还':
      return 'success'
    case '借阅中':
      return 'warning'
    case '已逾期':
      return 'danger'
    default:
      return 'info'
  }
}

// 获取状态文本
const getStatusText = (status: string) => {
  return status
}

onMounted(() => {
  fetchBorrowingHistory()
})
</script>

<template>
  <div class="borrowing-history">
    <!-- 导航栏 -->
    <header class="header">
      <div class="header-content">
        <div class="header-left">
          <el-button type="text" @click="goBack" class="back-button">
            <el-icon><ArrowLeft /></el-icon>
            返回
          </el-button>
          <div class="logo">
            <img src="https://lovechronicle.oss-cn-zhangjiakou.aliyuncs.com/book.jpg" alt="Logo" class="logo-img">
            <span class="logo-text">借阅历史</span>
          </div>
        </div>
      </div>
    </header>

    <!-- 搜索和筛选区域 -->
    <div class="search-filter-section">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            v-model="searchQuery"
            placeholder="搜索书名或作者..."
            clearable
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-col>
        <el-col :span="6">
          <el-select v-model="filterStatus" placeholder="借阅状态" clearable>
            <el-option label="全部" value="" />
            <el-option label="借阅中" value="借阅中" />
            <el-option label="已归还" value="已归还" />
            <el-option label="已逾期" value="已逾期" />
          </el-select>
        </el-col>
        <el-col :span="8">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
          />
        </el-col>
        <el-col :span="2">
          <el-button type="primary" @click="handleFilter">筛选</el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 借阅历史列表 -->
    <div class="history-list" v-loading="loading">
      <el-empty v-if="borrowingHistory.length === 0" description="暂无借阅记录" />
      <template v-else>
        <el-card v-for="record in borrowingHistory" 
                :key="record.id" 
                class="history-item"
                shadow="hover">
          <div class="history-item-content">
            <div class="book-info">
              <img :src="record.coverImage" alt="book cover" class="book-cover">
              <div class="book-details">
                <h3 class="book-title">{{ record.bookTitle }}</h3>
                <p class="book-author">
                  <el-icon><User /></el-icon>
                  作者：{{ record.author }}
                </p>
                <p class="borrow-date">
                  <el-icon><Calendar /></el-icon>
                  借阅日期：{{ record.borrowDate }}
                </p>
                <p class="return-date">
                  <el-icon><Calendar /></el-icon>
                  归还日期：{{ record.returnDate }}
                </p>
                <el-tag :type="getStatusType(record.status)" class="status-tag">
                  {{ getStatusText(record.status) }}
                </el-tag>
              </div>
            </div>
            <div class="operations">
              <el-button type="primary" @click="showDetails(record)">查看详情</el-button>
              <el-button 
                type="success" 
                v-if="record.status === 'borrowing'"
                @click="handleRenew(record)">
                申请续借
              </el-button>
            </div>
          </div>
        </el-card>
      </template>

      <!-- 分页 -->
      <div class="pagination-container" v-if="borrowingHistory.length > 0">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </div>

    <!-- 书籍详情对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="书籍详情"
      width="50%"
      :before-close="() => dialogVisible = false"
    >
      <div v-if="selectedBook" class="book-detail">
        <div class="book-detail-header">
          <img :src="selectedBook.coverImage" alt="book cover" class="detail-cover">
          <div class="detail-info">
            <h2>{{ selectedBook.bookTitle }}</h2>
            <p class="detail-author">作者：{{ selectedBook.author }}</p>
            <p class="detail-dates">借阅日期：{{ selectedBook.borrowDate }}</p>
            <p class="detail-dates">归还日期：{{ selectedBook.returnDate }}</p>
            <el-tag :type="getStatusType(selectedBook.status)">
              {{ getStatusText(selectedBook.status) }}
            </el-tag>
          </div>
        </div>
        <div class="book-description">
          <h3>图书简介</h3>
          <p>{{ selectedBook.description }}</p>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
          <el-button 
            type="primary" 
            v-if="selectedBook?.status === 'borrowing'"
            @click="handleRenew(selectedBook)">
            申请续借
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.borrowing-history {
  min-height: 100vh;
  background-color: #f2f2f2;
}

.header {
  background-color: #f5f5f5;
  padding: 15px 0;
  color: #333;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.header-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 20px;
}

.back-button {
  color: #666;
  display: flex;
  align-items: center;
  gap: 5px;
}

.logo {
  display: flex;
  align-items: center;
  gap: 10px;
}

.logo-img {
  width: 120px;
  height: 50px;
  object-fit: contain;
}

.logo-text {
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.search-filter-section {
  max-width: 1200px;
  margin: 20px auto;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.history-list {
  max-width: 1200px;
  margin: 20px auto;
  padding: 0 20px;
}

.history-item {
  margin-bottom: 20px;
  border-radius: 8px;
}

.history-item-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.book-info {
  display: flex;
  gap: 20px;
}

.book-cover {
  width: 120px;
  height: 160px;
  object-fit: cover;
  border-radius: 4px;
}

.book-details {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.book-title {
  margin: 0;
  font-size: 18px;
  color: #333;
}

.book-author, .borrow-date, .return-date {
  margin: 0;
  color: #666;
  display: flex;
  align-items: center;
  gap: 5px;
}

.status-tag {
  margin-top: 8px;
}

.operations {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.book-detail {
  padding: 20px;
}

.book-detail-header {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.detail-cover {
  width: 200px;
  height: 280px;
  object-fit: cover;
  border-radius: 8px;
}

.detail-info {
  flex: 1;
}

.detail-info h2 {
  margin: 0 0 15px 0;
  color: #333;
}

.detail-author, .detail-dates {
  margin: 8px 0;
  color: #666;
}

.book-description {
  margin-top: 20px;
}

.book-description h3 {
  margin-bottom: 10px;
  color: #333;
}

.book-description p {
  color: #666;
  line-height: 1.6;
}

/* Element Plus 组件样式覆盖 */
:deep(.el-input__wrapper) {
  box-shadow: none !important;
}

:deep(.el-button--text) {
  padding: 0;
}

:deep(.el-dialog__body) {
  padding: 0;
}

/* 添加分页样式 */
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  padding: 0 20px;
}
</style> 